<?php

namespace App\Http\Controllers\Admin;

use App\CodeResponse;
use App\Http\Controllers\Controller;
use App\Models\Certificate;
use App\Models\ExamCategory;
use App\Models\ExamPaper;
use App\Models\ExamPaperQuestion;
use App\Models\ExamQuestionOption;
use App\Models\UserExamRecord;
use App\Models\UserQuestionRecord;
use App\Models\Users;
use App\Services\CertificationExaminationService;
use App\Services\ExamPaperService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class CertificationExaminationController extends AdminController
{
    //认证考试试题数量
    public function  getCertificationExaminationInfo(Request $request){
        $validator = Validator::make($request->all(), [
            'certificate_id' => 'required|integer|digits_between:1,20|min:1',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $certificate_id = $request->input('certificate_id');
        $examPaper = ExamPaper::where('certificate_id',$certificate_id)->first();
        $users_id = Auth::id();
        if(!isset($users_id)){
            return $this->success($arr = [101, '未登录不能进行答题']);
        }
        if(!isset($examPaper->id)) {
            return $this->fail(CodeResponse::PAGE_INVALID);
        }
        $userExamRecord = UserExamRecord::where('exam_paper_id',$examPaper->id)
            ->where('certificate_id',$certificate_id)
            ->where('users_id',$users_id)->first();
        if(isset($userExamRecord->is_submitted) && $userExamRecord->is_submitted == 1){
            return $this->fail(CodeResponse::EXAMINATION_COMPLETE);
        }else{
            if(isset($userExamRecord->created_at)){
                //答题时间
                $currentDateTime = Carbon::now(); //当前时间
                // 计算考试用了多少分钟
                $timeElapsedInMinutes = $currentDateTime->diffInMinutes($userExamRecord->created_at);
                //计算考试还剩多长时间
                if(($examPaper->time_limit - $timeElapsedInMinutes) <0){
                    return $this->fail(CodeResponse::EXAMINATION_COMPLETE);
                }
            }
            $arr = CertificationExaminationService::getInstance()->certificationExaminationInfo($examPaper->id);
        }

//
//        if($examPaper){
//            $arr = CertificationExaminationService::getInstance()->certificationExaminationInfo($examPaper->id);
//        }else{
//            $arr =  [
//                'singleChoiceCount' => 0,
//                'multipleChoiceCount' => 0,
//                'estimateCount' => 0,
//                'fillBlankCount' => 0,
//                'shortAnswerCount' => 0,
//                'totalQuestions' => 0,
//            ];
//        }
        return $this->success($arr);
    }
    //认证考试试题
    public function certificationQuestions(Request $request){
        $users_id = Auth::id();
        if(!isset($users_id)){
            return $this->success($arr = [101, '未登录不能进行答题']);
        }
        $validator = Validator::make($request->all(), [
            'certificate_id' => 'required|integer|digits_between:1,20|min:1',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $certificate_id = $request->input('certificate_id');
        $certificate = Certificate::find($certificate_id);
        if(!isset($certificate)){
            return $this->fail(CodeResponse::CERTIFICATE_INVALID);
        }
        $examPaper = ExamPaper::where('certificate_id',$certificate_id)->first();
        if(!isset($examPaper)){
            return $this->fail(CodeResponse::PAGE_INVALID);
        }
        $users = Users::find($users_id);

        $userExamRecordObj = UserExamRecord::where('exam_paper_id',$examPaper->id)
            ->where('certificate_id',$certificate_id)
            ->where('users_id',$users_id)->first();
        if(!isset($userExamRecordObj->id)){
            $userExamRecord = new UserExamRecord();
            $userExamRecord->users_id = $users_id;
            $userExamRecord->username = $users->name;
            $userExamRecord->exam_paper_id = $examPaper->id;
            $userExamRecord->exam_paper_name = $examPaper->name;
            $userExamRecord->certificate_id = $certificate_id;
            $userExamRecord->certificate_name = isset($certificate) ? $certificate->name : '';
            $userExamRecord->is_submitted = 0; // 是否提交 0 未提交 1提交
            $userExamRecord->score = 0;
            $userExamRecord->take_time = 0;// 用时
            $userExamRecord->save();
            $givenTimeLimit = $examPaper->time_limit;
        }else{
            $currentDateTime = Carbon::now(); //当前时间
            $givenTimeLimit = 0;
            if(isset($userExamRecordObj->created_at)){
                // 计算考试用了多少分钟
                $timeElapsedInMinutes = $currentDateTime->diffInMinutes($userExamRecordObj->created_at);
                //计算考试还剩多长时间
                if(($examPaper->time_limit - $timeElapsedInMinutes) <0){
                    $givenTimeLimit = 0;
                }else{
                    $givenTimeLimit = $examPaper->time_limit - $timeElapsedInMinutes;
                }
            }

        }

        //获取试卷试题
        $examCategory = ExamCategory::where('id', $examPaper->exam_category_id)->first(); //试卷类别
        $certificate = Certificate::where('id', $examPaper->certificate_id	)->first();//证书

        $examPaperArr = [
            'categoryName' => isset($examCategory) ? $examCategory->name : '',
            'certificateName' => isset($certificate) ? $certificate->name : '',
            'examPaperId' => $examPaper->id,
            'is_submitted' => isset($userExamRecordObj->is_submitted)
                ? $userExamRecordObj->is_submitted
                : '' ,
            'examPaperName' => $examPaper->name,
            'startTime' => isset($userExamRecordObj->created_at)
                           ? $userExamRecordObj->created_at
                           : 0 ,
            'givenTimeLimit' => $givenTimeLimit,

        ];
        $arr = CertificationExaminationService::getInstance()
            ->paperQuestion($users_id,$certificate_id,$examPaper->id);
        $arr = array_merge($examPaperArr,$arr);

        return $this->success($arr);
    }
    //认证考试左侧答题进度
    public function answerProgress(Request $request){
        $users_id = Auth::id();
        if(!isset($users_id)){
            return $this->success($arr = [101, '未登录不能进行答题']);
        }
        $validator = Validator::make($request->all(), [
            'certificate_id' => 'required|integer|digits_between:1,20|min:1',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $certificate_id = $request->input('certificate_id');
        $examPaper = ExamPaper::where('certificate_id',$certificate_id)->first();
        if($examPaper){
            $arr = CertificationExaminationService::getInstance()->answerProgress($users_id,$examPaper->id);
        }else{
            $arr = [105, '不存在试卷'];
        }
        return $this->success($arr);

    }
    //保存考生的试卷
    public function savePage(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'certificate_id' => 'required|integer|digits_between:1,20|min:1',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $certificate_id = $request->input('certificate_id');
        $certificate = Certificate::find($certificate_id);
        if(!isset($certificate)){
            return $this->fail(CodeResponse::CERTIFICATE_INVALID);
        }

        $users_id = Auth::id();
        if(!isset($users_id)){
            return $this->success( [101, '未登录不能进行答题']);
        }

        $users = Users::find($users_id);
        $userExamRecordId = -1;
        if(isset($users)){
            $examPaper = ExamPaper::where('certificate_id',$certificate_id)->first();
            if(!isset($examPaper)){
                return $this->fail(CodeResponse::PAGE_INVALID);
            }

            $userExamRecord = new UserExamRecord;
            $userExamRecord->users_id = $users_id;
            $userExamRecord->username = $users->name;
            $userExamRecord->exam_paper_id = $examPaper->id;
            $userExamRecord->exam_paper_name = $examPaper->name;
            $userExamRecord->certificate_id = $certificate_id;
            $userExamRecord->certificate_name = isset($certificate) ? $certificate->name : '';
            $userExamRecord->is_submitted = 0; // 是否提交 0 未提交 1提交
            $userExamRecord->score = 0;
//            $userExamRecord->take_time = 0;// 用时
            $userExamRecord->save();
            $userExamRecordId = $userExamRecord->id;
        }
        return $this->success($userExamRecordId);
    }
    //保存考试答题
    public function savePageQuestion(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'exam_paper_id' => 'required|integer|digits_between:1,20|min:1',
            'certificate_id' => 'required|integer|digits_between:1,20|min:1',
            'exam_paper_question_id' => 'required|integer|digits_between:1,20|min:1',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $exam_paper_id= $request->input('exam_paper_id');
        $certificate_id = $request->input('certificate_id');
        $exam_paper_question_id = $request->input('exam_paper_question_id');
        $userAnswerArr= $request->input('user_answer');
        $userAnswerArr = is_array($userAnswerArr) ? $userAnswerArr : json_decode($userAnswerArr,true);
        $user_answer = is_array($userAnswerArr) ? implode(',',$userAnswerArr) : '';
        $subjectivity_question_con= $request->input('subjectivity_question_con');
        $users_id = Auth::id();
        if(!isset($users_id)){
            return $this->success($arr = [101, '未登录不能进行答题']);
        }
        $examPaper = ExamPaper::find($exam_paper_id);
        $userExamRecord = UserExamRecord::where('exam_paper_id',$examPaper->id)
            ->where('certificate_id',$certificate_id)
            ->where('users_id',$users_id)->first();
        //答题时间
        $currentDateTime = Carbon::now(); //当前时间
        // 计算考试用了多少分钟
        $timeElapsedInMinutes = $currentDateTime->diffInMinutes($userExamRecord->created_at);
        //计算考试还剩多长时间
        if(($examPaper->time_limit - $timeElapsedInMinutes) <0){
            return $this->fail(CodeResponse::EXAMINATION_OVERTIME);
        }

        $users = Users::find($users_id);
        $userExamQuestionRecordId = -1;

        if(isset($users)){
            $examPaperQuestion = ExamPaperQuestion::find($exam_paper_question_id);
            $examQuestionOption = ExamQuestionOption::where('exam_paper_question_id',$exam_paper_question_id)
            ->where('is_correct',1)->get();
            $examOptionIdArr = [];
            foreach ($examQuestionOption as $v) {
                array_push($examOptionIdArr, $v->id);
            }
            if (count($userAnswerArr) === count($examOptionIdArr) && !array_diff($userAnswerArr, $examOptionIdArr) && !array_diff($examOptionIdArr, $userAnswerArr)) {
                $is_correct = 1;
            } else {
                $is_correct = 0;
            }
            $userQuestionRecordObj = UserQuestionRecord::where('exam_paper_id',$exam_paper_id)
                ->where('exam_paper_question_id',$exam_paper_question_id)
                ->where('users_id',$users_id)->first();

            if(isset($userQuestionRecordObj->id) && $userQuestionRecordObj->id > 0){
                $userQuestionRecord = UserQuestionRecord::find($userQuestionRecordObj->id);
            }else{
                $userQuestionRecord = new UserQuestionRecord();
            }
            $userQuestionRecord->users_id = $users_id;
            $userQuestionRecord->username = $users->name;
            $userQuestionRecord->exam_paper_id = $exam_paper_id;
            $userQuestionRecord->certificate_id = $certificate_id;
            $userQuestionRecord->exam_paper_question_id= $exam_paper_question_id;
            $userQuestionRecord->question_type= $examPaperQuestion->question_type;
            $userQuestionRecord->user_answer = $user_answer;
            $userQuestionRecord->subjectivity_question_con = $subjectivity_question_con;
            if($is_correct == 1){
                $userQuestionRecord->score = $examPaperQuestion->score;
                $userQuestionRecord->is_correct = 1;
            }else{
                $userQuestionRecord->is_correct =0;
                $userQuestionRecord->score = 0;
            }
            $userQuestionRecord->save();
            $userExamQuestionRecordId = $userQuestionRecord->id;
        }

        return $this->success($userExamQuestionRecordId);
    }
    //考试结果
    function paperResult(Request $request){
        $validator = Validator::make($request->all(), [
            'exam_paper_id' => 'required|integer|digits_between:1,20|min:1',
            'certificate_id' => 'required|integer|digits_between:1,20|min:1',
        ]);
        if ($validator->fails()) {
            return $this->fail(CodeResponse::PARAM_ILLEGAL);
        }
        $exam_paper_id= $request->input('exam_paper_id');
        $certificate_id = $request->input('certificate_id');
        $users_id = Auth::id();
        if(!isset($users_id)){
            return $this->success($arr = [101, '未登录不能进行答题']);
        }
        $arr = ExamPaperService::getInstance()->userPaperResult($users_id,$exam_paper_id,$certificate_id);
        return $this->success($arr);

    }
    //用户证书信息
    function certificationInfo(Request $request){
        $users_id = Auth::id();
        if(!isset($users_id)){
            return $this->success($arr = [101, '未登录不能进行答题']);
        }
        $arr = ExamPaperService::getInstance()->certificationInfo($users_id);
        return $this->success($arr);

    }
      // 上传
    public function userQuestionFile(Request $request) {
        $url = config('filesystems.disks.userQuestionResult.url');
        $default = config('filesystems.disks.userQuestionResult.default');
        $pic =  ExamPaperService::getInstance()->upfile($request,$url,$default,'userQuestionResult');
        return $this->success([
                'pic'=>$pic,
            ]
        );
    }
}
